package com.example.service.Impl;

import com.example.entity.PageBean;
import com.example.entity.User;
import com.example.entity.vo.MonthData;
import com.example.entity.vo.UserStatistic;
import com.example.entity.vo.WeekData;
import com.example.entity.vo.WeekResponse;
import com.example.mapper.AdminMapper;
import com.example.service.AdminService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public PageBean pageUser(Integer page, Integer pageSize, String username, String email) {
        //设置分页参数
        PageHelper.startPage(page, pageSize);

        //执行查询
        List<User> empList = adminMapper.pageList(page, pageSize, username, email);
        Page<User> p = (Page<User>) empList;

        //计算总页数
        Integer pageCount = (int)p.getTotal() % pageSize == 0 ? (int)p.getTotal() / pageSize : (int)p.getTotal() / pageSize + 1;

        //封装pageBean对象
        PageBean pageBean = new PageBean((int)p.getTotal(), p.getResult(), pageCount);
        return pageBean;
    }

    @Override
    public void deleteUser(Integer id) {
        adminMapper.deleteUser(id);
    }

    @Override
    public UserStatistic receiveUserStatistic() {
        Integer total = adminMapper.getTotal();
        Integer added = adminMapper.getadded();
        Integer active = adminMapper.getActive();
        Float totalRate = adminMapper.getTotalRate();
        Float addedRate = adminMapper.getAddedRate();
        Float activeRate = adminMapper.getActiveRate();
        Integer average;
        Float averageRate;
        if(adminMapper.getAverage()!=null){
            average = adminMapper.getAverage();
        } else {
            average = 0;
        }
        if (adminMapper.getAverageRate()!=null){
            averageRate = adminMapper.getAverageRate();
        } else{
            averageRate = 0.0F;
        }
        return new UserStatistic(total, added, active, average, totalRate, addedRate, activeRate, averageRate);
    }

    @Override
    public MonthData getMonthsData() {
        List<String> months = adminMapper.getMonthsData();
        List<Integer> total = adminMapper.getTotals();
        return new MonthData(months,total);
    }

    @Override
    public WeekResponse getWeekData() {
        List<WeekData> weekDataList = adminMapper.getWeekData();
        List<Date> weeks = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (WeekData weekData : weekDataList) {
            weeks.add(weekData.getLoginDate());
            counts.add(weekData.getLoginCount());
        }
        return new WeekResponse(weeks, counts);
    }
}
